package utils

import (
	"go-project/common/base/req"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

func Page[T any](tx *gorm.DB, list *[]*T, page *req.Pager) (count int64, err error) {
	offset := page.GetOffset()
	countResult := tx.Count(&count)
	if countResult.Error != nil {
		return 0, countResult.Error
	}
	tx.Order(clause.OrderByColumn{
		Column: clause.Column{Name: page.Order},
		Desc:   !page.Asc,
	})
	listResult := tx.Offset(offset).Limit(page.PageSize).Find(list)
	if listResult.Error != nil {
		return 0, listResult.Error
	}
	return
}
